package com.hzjh.h5mall.ui.ads

import android.view.View
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.hzjh.base.ext.R
import com.hzjh.base.ext.frame.JHBaseActivity
import com.hzjh.base.ext.route.RouteUrl
import com.hzjh.base.ext.utils.DownloadUtils
import com.hzjh.base.ext.utils.NumberUtils
import com.hzjh.base.ext.widget.dialog.JHCopywritingDialog
import com.hzjh.base.router.ext.navigationTo
import com.hzjh.base.style.view.dialog.ConfirmDialog
import com.hzjh.base.style.weight.ToastKt.toastCenter
import com.hzjh.base.utils.function.visibleOrGone
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.utils.other.CommUtils
import com.hzjh.h5mall.adapter.AdBannerAdapter
import com.hzjh.h5mall.bean.AdOrderStatus
import com.hzjh.h5mall.bean.AdStatus
import com.hzjh.h5mall.bean.ads.AdsDetailBean
import com.hzjh.h5mall.databinding.ActivityAdsDetailBinding
import com.hzjh.h5mall.model.ads.AdsModel
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.CircleIndicator

@Route(path = RouteUrl.ADS_ACTIVITY_DETAIL)
class AdsDetailActivity : JHBaseActivity<ActivityAdsDetailBinding,AdsModel>() {
    @JvmField
    @Autowired(name = RouteUrl.PARAMS_ADS_ID)
    var mAdsId: String = "" //广告id
    @JvmField
    @Autowired(name = RouteUrl.PARAMS_TASK_ID)
    var mTaskId: String = "" //任务id

    private val bannerAdapter: AdBannerAdapter by lazy {
        AdBannerAdapter(viewModel.banner.value!!,this){ adsBannerBean ->
            val jumpUrl = adsBannerBean.img
            if(adsBannerBean.type == 11){
                //跳转图片详情
                navigationTo(RouteUrl.PREVIEW_ACTIVITY_IMAGE){
                    withString(RouteUrl.PARAMS_IMAGE_URL,jumpUrl)
                }
            }else {
                //跳转视频详情
                navigationTo(RouteUrl.PREVIEW_ACTIVITY_VIDEO) {
                    withString(RouteUrl.PARAMS_VIDEO_URL, jumpUrl)
                }
            }
        }
    }

    override fun initData() {
        if(!CheckUtils.isEmpty(mTaskId)){
            viewModel.reqAdsOrderDetail(mTaskId)
        }else {
            viewModel.reqAdsDetail(mAdsId)
        }
    }

    override fun initView() {
        viewBinding.bannerAds.setAdapter(bannerAdapter).isAutoLoop(false)
            .setIndicator(CircleIndicator(this),false)
            .setIndicatorGravity(IndicatorConfig.Direction.RIGHT)
            .addOnPageChangeListener(object : com.youth.banner.listener.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                }

                override fun onPageScrollStateChanged(state: Int) {
                    if (state == ViewPager2.SCROLL_STATE_IDLE) {
                        val count = viewModel.banner.value!!.size
                        viewBinding.tvBannerIndicator.text = "${viewBinding.bannerAds.currentItem%count+1}/$count"
                    }
                }
            })

        viewBinding.ivBack.setOnClickListener {
            finish()
        }
        viewBinding.ivDownload.setOnClickListener {
            //下载素材
            viewModel.banner.value?.let { adsBannerBane ->
                DownloadUtils.download(this,adsBannerBane.map { it.img }){result->
                    toastCenter(if(result)CommUtils.getString(R.string.jh_download_success) else CommUtils.getString(R.string.jh_download_error))
                }
            }
        }
        viewBinding.tvMoreCopy.setOnClickListener {
            //复制
            JHCopywritingDialog(viewModel.adsDetailBean.value?.comment?:"").show(supportFragmentManager,"tvMoreCopy")
        }
        viewBinding.btnAccept.setOnClickListener {
            //接单
            ConfirmDialog.Builder(this)
                .setMessage(CommUtils.getString(R.string.jh_accept_task))
                .setCancelButton(CommUtils.getString(R.string.jh_turn_off)){ dialog, _ ->
                    dialog.dismiss()
                }.setSureButton(CommUtils.getString(R.string.jh_Accept)) { dialog, _ ->
                    viewModel.reqAdsAccept(mAdsId)
                    dialog.dismiss()
                }.setCanCancel(true).create().show()
        }
        viewBinding.btnRelease.setOnClickListener {
            //放弃
            ConfirmDialog.Builder(this)
                .setMessage(CommUtils.getString(R.string.jh_accept_task))
                .setCancelButton(CommUtils.getString(R.string.jh_turn_off)){ dialog, _ ->
                    dialog.dismiss()
                }.setSureButton(CommUtils.getString(R.string.jh_release)) { dialog, _ ->
                    viewModel.reqAdsCancel(mTaskId)
                    dialog.dismiss()
                }.setCanCancel(true).create().show()
        }
        viewBinding.btnRevenue.setOnClickListener {
            //结算
            navigationTo(RouteUrl.ADS_ORDER_ACTIVITY_DETAIL){
                withString(RouteUrl.PARAMS_TASK_ID,mTaskId)
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.adsDetailBean.observe(this){
            //Banner
            viewModel.setBannerData(it.images)
            //价格
            viewBinding.tvPrice.text = it.price
            //已接数量
            viewBinding.tvCounts.text = NumberUtils.formatNumber(it.views)
            //平台
            viewBinding.rvPlatform.setData(it.platforms.map {platform -> platform.remarks })
            //Copywriting
            viewBinding.tvCopyContent.text = it.comment
            //状态，state 状态，-1自定义的状态 0进行中，10待审核，20已审核，25待打款，30财务打款完成，99拒绝,98超时,97取消
            when(it.state){
                AdOrderStatus.UNACCEPT.value->viewModel.setStatus(AdStatus.UNACCEPT)
                AdOrderStatus.ACCEPT.value,
                AdOrderStatus.WAITING.value,
                AdOrderStatus.REVIEWED.value,
                AdOrderStatus.PENDING_PAY.value->viewModel.setStatus(AdStatus.ACCEPT)
                AdOrderStatus.COMPLETE.value->viewModel.setStatus(AdStatus.COMPLETE)
                AdOrderStatus.CANCEL.value,
                AdOrderStatus.TIMEOUT.value,
                AdOrderStatus.REJECT.value->viewModel.setStatus(AdStatus.CANCEL)
            }

        }
        viewModel.status.observe(this){
            //状态改变
            changeStateView(it,viewModel.adsDetailBean.value)
        }
        viewModel.acceptTaskId.observe(this){
            //接受广告成功
            mTaskId=it
            viewModel.reqAdsOrderDetail(mTaskId)
        }

        viewModel.banner.observe(this){
            bannerAdapter.notifyDataSetChanged()
            viewBinding.tvBannerIndicator.text = "1/${viewModel.banner.value!!.size}"
        }
    }

    private fun changeStateView(status: AdStatus,adsDetailBean: AdsDetailBean?){
        when(status){
            AdStatus.ACCEPT -> {
                viewBinding.tvAdStatus.visibleOrGone(true){
                    text = CommUtils.getString(R.string.jh_accepted_btn)
                }
                viewBinding.btnRelease.visibleOrGone(true)
                viewBinding.btnAccept.visibleOrGone(false)
                viewBinding.btnRevenue.visibleOrGone(true)
                viewBinding.btnRevenue.isEnabled=true
                viewBinding.tvDescTitle1.text=CommUtils.getString(R.string.jh_dead_line)
                viewBinding.tvDescTitle2.text=CommUtils.getString(R.string.jh_remaining_time)
                viewBinding.tvDescValue1.text="${adsDetailBean?.endTime}"
                viewBinding.tvDescValue2.text=NumberUtils.formatTime(adsDetailBean?.sysTime?:"",adsDetailBean?.overTime?:"")
            }
            AdStatus.CANCEL -> {
                viewBinding.tvAdStatus.visibleOrGone(true){
                    text = CommUtils.getString(R.string.jh_canceled_btn)
                }
                viewBinding.btnRelease.visibleOrGone(false)
                viewBinding.btnAccept.visibleOrGone(false)
                viewBinding.btnRevenue.visibleOrGone(false)
                viewBinding.tvDescTitle1.text=CommUtils.getString(R.string.jh_cycle)
                viewBinding.tvDescTitle2.text=CommUtils.getString(R.string.jh_accepted)
                viewBinding.tvDescValue1.text="${adsDetailBean?.daysNum} ${if(adsDetailBean?.daysType==0) CommUtils.getString(R.string.jh_days) else CommUtils.getString(R.string.jh_hours)}"
                viewBinding.tvDescValue2.text="${NumberUtils.formatNumber(adsDetailBean?.counts?:0)}"
            }
            else -> {
                viewBinding.tvAdStatus.visibility = View.GONE
                viewBinding.btnRelease.visibleOrGone(false)
                viewBinding.btnAccept.visibleOrGone(true)
                viewBinding.btnRevenue.visibleOrGone(true)
                viewBinding.btnRevenue.isEnabled=false
                viewBinding.tvDescTitle1.text=CommUtils.getString(R.string.jh_cycle)
                viewBinding.tvDescTitle2.text=CommUtils.getString(R.string.jh_accepted)
                viewBinding.tvDescValue1.text="${adsDetailBean?.daysNum} ${if(adsDetailBean?.daysType==0) "Days" else "Hours"}"
                viewBinding.tvDescValue2.text="${NumberUtils.formatNumber(adsDetailBean?.counts?:0)}"
            }
        }
    }

    override fun initViewBinding(): ActivityAdsDetailBinding {
        return ActivityAdsDetailBinding.inflate(layoutInflater)
    }
}